/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.eolwral.osmonitor.messages;

import java.io.File;
import java.io.FileWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.eolwral.osmonitor.*;

public abstract class DebugBox extends Activity
{
	protected static final JNIInterface JNILibrary = JNIInterface.getInstance();

	protected BaseAdapter UpdateInterface = null;
	protected ListView InternalList = null;
	protected TextView EmptyMsg = null;
	protected TextView MsgCountText = null;
	
	/**
	 * The tab index for the current tab. This is used by Gesture Scroller to
	 * flip to the right page on swipe.
	 */
	protected int TabIndex = 0;

	private boolean FreezeIt = false;
	
	private DialogInterface.OnClickListener NullClickListener =
		new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
			}
		};
	
	// Gesture
	private GestureScroller gestureScanner;

	@Override
	public boolean onTouchEvent(MotionEvent me)
	{
		return gestureScanner.onTouchEvent(me);
	}

	// Refresh
	private Runnable runnable = new Runnable() {
		public void run()
		{
			if (!FreezeIt && JNILibrary.doDataLoad() == 1)
			{
				MsgCountText.setText(Integer.toString(getMessageCount()));

				if (EmptyMsg != null)
					EmptyMsg.setText("");

				UpdateInterface.notifyDataSetChanged();
			}
			handler.postDelayed(this, 1000);
		}
	};
	private Handler handler = new Handler();

	/**
	 * Gets the number of messages currently displayed.
	 * 
	 * @return
	 */
	protected abstract int getMessageCount();

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		// Request progress bar
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.debuglayout);

		InternalList = (ListView) findViewById(R.id.debuglist);
		EmptyMsg = (TextView) findViewById(R.id.debugempty);
		MsgCountText = (TextView) findViewById(R.id.debugmsgcounts);
		gestureScanner = new GestureScroller(this, InternalList, TabIndex);

		// Freeze
		CheckBox Freeze = (CheckBox) findViewById(R.id.debugmsgfreeze);
		Freeze.setOnClickListener(new OnClickListener() {
			public void onClick(View v)
			{
				if (FreezeIt)
					FreezeIt = false;
				else
					FreezeIt = true;
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu optionMenu)
	{
		optionMenu.add(0, 2, 0, getResources().getString(R.string.menu_logexport));
		return true;
	}

	protected abstract void restorePrefs();

	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		restorePrefs();
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
		case 0:
			AlertDialog.Builder HelpWindows = new AlertDialog.Builder(this);
			HelpWindows.setTitle(R.string.app_name);
			HelpWindows.setMessage(R.string.help_info);
			HelpWindows.setPositiveButton(R.string.button_close, NullClickListener);

			WebView HelpView = new WebView(this);
			HelpView.loadUrl("http://wiki.android-os-monitor.googlecode.com/hg/phonehelp.html?r=b1c196ee43855882e59ad5b015b953d62c95729d");
			HelpWindows.setView(HelpView);

			return HelpWindows.create();
		case 1:
			LinearLayout Layout = new LinearLayout(this);
			Layout.setOrientation(LinearLayout.VERTICAL);
			Layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT));

			EditText FileName = new EditText(this);
			FileName.setId(100);

			CheckBox UseHTML = new CheckBox(this);
			UseHTML.setId(200);
			UseHTML.setText("HTML Format");

			Layout.addView(FileName, 0);
			Layout.addView(UseHTML, 1);

			return new AlertDialog.Builder(this)
					.setTitle(R.string.common_exportfile_title)
					.setView(Layout)
					.setPositiveButton(R.string.button_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton)
								{
									String FileName = ((EditText) ((AlertDialog) dialog)
											.findViewById(100)).getText()
											.toString();
									Boolean useHTML = ((CheckBox) ((AlertDialog) dialog)
											.findViewById(200)).isChecked();
									SaveLog(FileName, useHTML);
								}
							})
					.setNegativeButton(R.string.button_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton)
								{
									/* User clicked cancel so do some stuff */
								}
							}).create();

		case 2:
			LinearLayout FilterLayout = new LinearLayout(this);
			FilterLayout.setOrientation(LinearLayout.VERTICAL);
			FilterLayout.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

			Spinner LogLevel = new Spinner(this);
			LogLevel.setId(100);
			ArrayAdapter<?> LevelAdapter = ArrayAdapter.createFromResource(
					this, R.array.logcat_level_list,
					android.R.layout.simple_spinner_item);
			LevelAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			LogLevel.setAdapter(LevelAdapter);

			FilterLayout.addView(LogLevel, 0);

			return new AlertDialog.Builder(this)
					.setTitle(R.string.pref_filterlevel_text)
					.setView(FilterLayout)
					.setPositiveButton(R.string.button_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton)
								{
									long Level = ((Spinner) ((AlertDialog) dialog)
											.findViewById(100))
											.getSelectedItemId() + 1;
									if (Level == 1)
										Level = 0;
									JNILibrary.SetLogcatLevel((int) Level);
								}
							})
					.setNegativeButton(R.string.button_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton)
								{
								}
							}).create();
		}

		return null;
	}

	/**
	 * Formats the log message with the given index to a string.
	 * 
	 * @param index
	 *            The index of the message to retrieve.
	 * @param html
	 *            If true, we want the formatted message to be in HTML.
	 * @return The formatted log message.
	 */
	protected abstract String getLogMessage(int index, boolean html);

	private void SaveLog(String FileName, Boolean useHTML)
	{
		if (FileName.trim().equals(""))
			return;

		try
		{
			File LogFile = new File(Environment.getExternalStorageDirectory()
					.getPath() + FileName);

			if (LogFile.exists())
			{
				new AlertDialog.Builder(this)
						.setTitle(R.string.app_name)
						.setMessage(R.string.common_exportexist_title)
						.setPositiveButton(R.string.button_ok, NullClickListener)
						.create().show();
				return;
			}

			LogFile.createNewFile();

			int LogCount = getMessageCount();

			FileWriter TextFile = new FileWriter(LogFile);

			if (useHTML)
				TextFile.write("<html>\n<body>\n<table>\n");

			for (int i = 0; i < LogCount; i++)
			{
				String TextLine = getLogMessage(i, useHTML);
				TextFile.write(TextLine);
			}

			if (useHTML)
				TextFile.write("</table>\n</body>\n</html>\n");

			TextFile.close();

		}
		catch (Exception e)
		{
			new AlertDialog.Builder(this)
					.setTitle(R.string.app_name)
					.setMessage(e.getMessage())
					.setPositiveButton(R.string.button_ok, NullClickListener)
					.create().show();

			return;
		}

		new AlertDialog.Builder(this)
				.setTitle(R.string.app_name)
				.setMessage(R.string.common_exportdone_title)
				.setPositiveButton(R.string.button_ok, NullClickListener)
				.create().show();

		return;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);
		switch (item.getItemId())
		{
		case 2:
			this.showDialog(1);
			break;

		case 3:
			this.showDialog(2);
			break;
		}

		return true;
	}

	@Override
	public void onPause()
	{
		handler.removeCallbacks(runnable);
		JNILibrary.doTaskStop();

		super.onPause();
	}

	@Override
	protected void onResume()
	{
		handler.post(runnable);
		super.onResume();
	}
}
